package cloudspace.vm.javassist;

import java.util.List;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.Translator;

import org.apache.log4j.Logger;

import cloudspace.vm.VM;


/**
 * The Class ConfigurableTranslator. This is a special translator that can be
 * configured with a configuration file.
 */
public class ConfigurableTranslatorLoader implements Translator
{

    /** The custom expr. */
    private CustomExprEditor cusExpr;

    protected Logger logger = Logger.getLogger( ConfigurableTranslatorLoader.class );


    /**
     * Instantiates a new configurable translator.
     * 
     * @param current
     *            the current
     */
    public ConfigurableTranslatorLoader( ConfigParser current )
    {
        List<CommandInterface> editConfigs = current.getCommands();
        cusExpr = new CustomExprEditor( editConfigs );

    }


    /*
     * (non-Javadoc)
     * 
     * @see javassist.Translator#onLoad(javassist.ClassPool, java.lang.String)
     */
    public void onLoad( ClassPool pool, String classname )
        throws NotFoundException,
        CannotCompileException
    {
        try
        {
            CtClass clazz = pool.get( classname );
            logger.trace( "Javassist Loader Attempting to load " + classname );
            if ( classname.startsWith( "auto.generated." ) )
            {
                logger.debug( "Javassist Loader is rewriting autogenerated class:  "
                    + classname );
                rewriteClass( clazz );
            }
            else
            {
                if ( VM.currentVM().isLocalClass( classname ) )
                {
                    logger.debug( "Rewriting class:  " + classname );
                    rewriteClass( clazz );
                }
            }

        }
        catch ( NotFoundException e )
        {
            // Nothing happens here because this method is called before
            // javasisst knows if the class belongs to this loader.
            ;
        }
    }


    private void rewriteClass( CtClass clazz ) throws CannotCompileException
    {
        cusExpr.staticEdits( clazz );
        if ( !clazz.isFrozen() )
        {
            clazz.instrument( cusExpr );
        }
    }


    /*
     * (non-Javadoc)
     * 
     * @see javassist.Translator#start(javassist.ClassPool)
     */
    public void start( ClassPool pool )
        throws NotFoundException,
        CannotCompileException
    {
        // TODO Auto-generated method stub

    }

}
